/**
 * api调用接口的通用方法
 */

import axios from 'axios'
import {PopupCommon} from './popupCommon'
import moment from 'moment'
import {setToken, getToken} from '@/libs/util'
export const ImageAddress = 'http://39.105.187.42:8018'
/**
 * 文件服务器地址，环境不同，打包时替换下
 */
// export const fileAddress = "https://ccdc.linghangdzg.com"
export const fileAddress = 'http://39.105.187.42:8018'
// export const fileAddress = "http://42.192.50.79";
/**
 * 打印标签地址，环境不同，打包时替换下
 */
// export const printAddress = "https://ccdc.linghangdzg.com"
export const printAddress = 'http://39.105.187.42:8018'

export const getUser = () => {
    return JSON.parse(localStorage.getItem('userInfo'))
}
export function md5(message) {
    // 引入 crypto-js 库
    const CryptoJS = require('crypto-js')
    // 使用 MD5 加密
    const md5Hash = CryptoJS.MD5(message).toString()
    return md5Hash
}

/**
 * 请求接口的方法
 * @param {*} url
 * @param {*} type post/get
 * @param {*} data
 */
export const AjaxCommon = async (url, type, data, isSign = false, id = '') => {
    // // 待加密的字符串
    // const message = 'Hello, World!'
    // // 使用 MD5 加密
    // const md5Hash = md5(message)
    // 后台到秒
    // const Timestamp = moment().diff(moment('1970-01-01 00:00:00')) / 1000
    const Timestamp = parseInt(new Date().getTime() / 1000)
    const Nonce = parseInt(Math.random() * 1000000)
    // + PAY_SUM
    //    const sign= md5(getUser()?.orgId ?? '' + localStorage.getItem('token') ?? '' + Nonce + Timestamp )
    let headers = {
        token: getToken() ? getToken() : '',
        LoginName: getUser()?.username ?? '',
        OrgId: getUser()?.orgId ?? '',
        // 随机数
        Nonce: Nonce,
        // 时间戳
        Timestamp: Timestamp
    }

    // sign=md5(ORG_ID + token + Nonce + Timestamp + PAY_SUM)
    // 时间戳，自1970-01-01的0时至今的秒数，用于sign以及请求时间窗口验证，超时30秒失效
    // let routeUrl = ""
    // routeJs 不需要，有个统一的js维护
    // const pathname = window.location.pathname.split("/")
    // routeUrl = pathname[pathname.length - 1]
    let jsonData = undefined
    if (type == 'postForm') {
        let forms = new FormData()
        Object.keys(data).map((t) => {
            forms.append(t, data[t])
        })
        jsonData = await axios
            .post(url, forms, {
                headers: headers,
                timeout: 1000 * 60
            })
            .catch((res) => {
                gotoCatchUrl(res.response)
            })
        return jsonData
    } else if (type == 'post') {
        if (isSign) {
            const s = headers.OrgId + headers.token + Nonce + Timestamp + data.ac_guid + id
            const sign = md5(s)
            console.log(s, sign, 'sign......')
            data['sgin'] = sign
        }
        let newData = JSON.parse(JSON.stringify(data))
        Object.keys(newData).map((t) => {
            newData[t] = encodeURIComponent(newData[t])
        })
        jsonData = await axios
            .post(url, data, {
                headers: headers,
                timeout: 1000 * 60
            })
            .catch((res) => {
                gotoCatchUrl(res.response)
            })
        return jsonData
    } else if (type == 'postGet') {
        jsonData = await axios
            .post(url, {
                headers: headers,
                timeout: 1000 * 60
            })
            .catch((res) => {
                gotoCatchUrl(res.response)
            })
        return jsonData
    } else if (type == 'get') {
        if (isSign && id) {
            const s = headers.OrgId + headers.token + Nonce + Timestamp + id
            console.log(s, 's...')
            const sign = md5(s)
            url += `&Sign=${sign}`
        }
        jsonData = await axios
            .get(url, {
                headers: {
                    timeout: 1000 * 60,
                    ...headers,
                    'Content-Type': 'application/json'
                }
            })
            .catch((res) => {
                gotoCatchUrl(res.response)
            })
        return jsonData
    } else if (type == 'getBody') {
        jsonData = await axios
            .get(url, {
                headers: {
                    ...headers
                    // 'Content-Type': 'application/json'
                },
                params: data,
                timeout: 1000 * 60
            })
            .catch((res) => {
                gotoCatchUrl(res.response)
            })
        return jsonData
    } else if (type == 'delete') {
        jsonData = await axios
            .delete(url, {
                headers: headers
            })
            .catch((res) => {
                gotoCatchUrl(res.response)
            })
        return jsonData
    } else if (type == 'deleteForm') {
        jsonData = await axios
            .delete(url, {
                headers: headers,
                data: data
            })
            .catch((res) => {
                gotoCatchUrl(res.response)
            })
        return jsonData
    } else if (type == 'put') {
        jsonData = await axios
            .put(url, data, {
                headers: headers,
                timeout: 1000 * 60
            })
            .catch((res) => {
                gotoCatchUrl(res.response)
            })
        return jsonData
    } else if (type == 'putForm') {
        let forms = new FormData()
        Object.keys(data).map((t) => {
            forms.append(t, data[t])
        })
        jsonData = await axios
            .put(url, forms, {
                headers: headers,
                timeout: 1000 * 60
            })
            .catch((res) => {
                gotoCatchUrl(res.response)
            })
        return jsonData
    }
}

const gotoCatchUrl = (jsonData) => {
    if (jsonData) {
        const esg = jsonData?.data?.msg ?? jsonData?.data?.Message ?? jsonData.Message
        if (jsonData.status == 401) {
            // 如果本来就在登录页面，无法跳转和提示
            // window.location.pathname
            if (window.location.hash == '#/') {
                return
            }
            // PopupCommon.notify('error', esg)
            setTimeout(() => {
                sessionStorage.setItem('ALLMENULIST', '')
                localStorage.removeItem('userInfo')
                sessionStorage.setItem('menuInfo', '')
                setToken('')
                localStorage.tagNaveList = ''
                window.location.href = '/'
            }, 1500)
        } else if (jsonData?.status != 200) {
            PopupCommon.notify('error', esg)
        }
    }
}

export const getProject = (url) => {
    return axios.get(url, {
        headers: {
            'X-Access-Token': localStorage.getItem('token')
        }
    })
}

/**
 * 请求接口的方法（下载excel模板的方法）
 * @param {*} url
 */
export const AjaxCommonExcelDownload = async (url) => {
    const Timestamp = parseInt(new Date().getTime() / 1000)
    const Nonce = parseInt(Math.random() * 1000000)
    let headers = {
        token: getToken() ? getToken() : '',
        LoginName: getUser()?.username ?? '',
        OrgId: getUser()?.orgId ?? '',
        // 随机数
        Nonce: Nonce,
        // 时间戳
        Timestamp: Timestamp
    }
    return axios({
        url: url,
        method: 'get',
        data: {},
        headers: headers,
        responseType: 'blob'
        // responseType: 'arraybuffer'
    })
}

/**
 * 设备单个写入的公共方法
 * @param {*} eqid 设备id
 * @param {*} sjx
 * @param {*} cs
 */
export const WriteSetRun = async (eqid, sjx, cs) => {
    const data = await AjaxCommon(`/api/Eq/WriteSetRun?eqid=${eqid}&sjx=${sjx}&cs=${cs}`, 'post', {})
    let isTrue = false
    if (data?.data?.Message == '1' || data?.data?.Message == 'ok') {
        isTrue = true
        // PopupCommon.notify('success', '操作成功')
    } else {
        PopupCommon.notify('error', '操作失败')
    }
    return isTrue
}
